use crate::handler::handler::send_response;
use crate::pkg::errno::code::Errno::{ErrDatabase, ErrTopicNotFound, IsOk};
use actix_web::{web, Responder, Result};

use crate::model::request::{TopicInfo, TopicSearch, ID};
use crate::model::topic;

// 创建topic
pub async fn create(t: web::Json<TopicInfo>) -> Result<impl Responder> {
    // 1.新增
    let create_t = topic::create_topic(&t).await;
    match create_t {
        Ok(_) => send_response(IsOk, Some(())).await,
        Err(_) => send_response(ErrDatabase, None).await,
    }
}

// 编辑
pub async fn edit(params: web::Json<TopicInfo>) -> Result<impl Responder> {
    // 判断id 是否存在
    if params.id.is_some() {
        // 查询 id是否存在
        let resp = topic::topic_detail(params.id.unwrap()).await;
        match resp {
            Ok(_) => {
                let edit_res = topic::edit_topic(&params).await;
                match edit_res {
                    Ok(_) => send_response(IsOk, Some(())).await,
                    Err(_) => send_response(ErrDatabase, None).await,
                }
            }
            Err(_) => send_response(ErrTopicNotFound, None).await,
        }
    } else {
        send_response(ErrTopicNotFound, None).await
    }
}

// 删除主题
pub async fn delete(params: web::Path<ID>) -> Result<impl Responder> {
    let res = topic::delete_topic(params.id).await;
    match res {
        Ok(()) => send_response(IsOk, Some(())).await,
        Err(_) => send_response(ErrDatabase, None).await,
    }
}

// 查询 详情
pub async fn detail(params: web::Path<ID>) -> Result<impl Responder> {
    let res = topic::topic_detail(params.id).await;
    match res {
        Ok(i) => send_response(IsOk, Some(i)).await,
        Err(_) => send_response(ErrTopicNotFound, None).await,
    }
}

// topic list
pub async fn list(params: web::Query<TopicSearch>) -> Result<impl Responder> {
    let list = topic::get_topic_list(&params).await;
    match list {
        Ok(i) => send_response(IsOk, Some(i)).await,
        Err(_) => send_response(ErrDatabase, None).await,
    }
}
